<?php

namespace common\model;

use think\model\RelationModel;
use think\module\Module;

class ChatUserModel extends RelationModel
{
    //自动验证
    protected $_validate = [
        ['chat_global_id', '', '', self::MUST_VALIDATE, 'require', self::MODEL_INSERT],//必须字段
        ['chat_global_id', '1,36', '', self::EXISTS_VALIDATE, 'length'],
        ['is_admin', [0, 1], '', self::EXISTS_VALIDATE, 'in'],
        ['allow_speak', [0, 1], '', self::EXISTS_VALIDATE, 'in'],
        ['user_id', '', '', self::MUST_VALIDATE, 'require', self::MODEL_INSERT],//必须字段
//        ['config', '', '', self::MUST_VALIDATE, 'require', self::MODEL_INSERT],//必须字段
        ['mute', ['yes', 'no'], '', self::EXISTS_VALIDATE, 'in'],
        ['favorite', ['yes', 'no'], '', self::EXISTS_VALIDATE, 'in']
    ];

    // 自动完成
    protected $_auto = [
        ['join_at', 'time', self::MODEL_INSERT, 'function'],
        ['config', 'json_encode', self::EXISTS_VALIDATE, 'function'],
        ['json', 'json_encode', self::EXISTS_VALIDATE, 'function'],

    ];

    // 隐藏字段
    protected $hidden = ['json'];

    // 自动完成后验证
    protected $_validate_after_auto = [
        ['user_id,chat_global_id', '', '', self::MUST_VALIDATE, 'unique'],
    ];

    /**
     * 获取器：自定义字段
     * @param $value
     * @param $data
     * @return array|mixed
     */
    public function getJsonAttr($value, $data)
    {
        // 当前模块的自定义字段配置
        $fieldDict = Module::$moduleDictData['field_index_by_code']['chat_user']['custom'];

        // 判断是否有值
        if (!empty($value)) {
            $jsonDictData = json_decode($value, true);
        } else {
            $jsonDictData = [];
        }

        // 把自定义值写入追加字段
        foreach ($fieldDict as $filed => $config) {
            if (array_key_exists($filed, $jsonDictData)) {
                $this->appendCustomField[$filed] = $jsonDictData[$filed];
            } else {
                // 没有值赋空值
                $this->appendCustomField[$filed] = "";
            }
        }

        return [];
    }

    /**
     * 获取器：加入时间
     * @param $value
     * @param $data
     * @return array|mixed
     */
//    public function getJoinAtAttr($value, $data)
//    {
//        if (!empty($value)) {
//            return get_format_date($value, 1);
//        }
//        return "";
//    }

    /**
     * config json
     * @param $value
     * @param $data
     * @return mixed
     */
    public function getConfigAttr($value, $data)
    {
        return json_decode($value, true);
    }


}
